// src/auth/jwt.strategy.ts
import { PrismaService } from '@app/prisma';
import { RedisService } from '@app/redis';
import { Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy, ExtractJwt } from 'passport-jwt';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly redisService: RedisService,
    private readonly prismaService: PrismaService,
    configService: ConfigService,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: configService.get('auth.jwt.token'), // 替换为你的 JWT 密钥
      ignoreExpiration: false, // 确保过期时间被检查
      passReqToCallback: true, // 传递 request 对象到 validate 方法
    });
  }

  async validate(request: Request, payload: { userId: string }) {
    const headers = request.headers;
    const authorization = headers['authorization'];
    const token = authorization?.split(' ')[1];
    // 从redis中获取token 拿到的话说明 token还是生效的
    const redisToken = await this.redisService.get(
      `xxx_token_${payload.userId}`,
    );
    if (redisToken == token) {
      const user = await this.prismaService.user.findUnique({
        where: {
          id: payload.userId,
        },
      });
      return user;
    }
    throw new UnauthorizedException();
  }
}
